package com.usian.skill.mq;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.common.CodeMsg;
import com.usian.skill.common.Result;
import com.usian.skill.pojo.SkillMessage;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.GoodsService;
import com.usian.skill.service.SkillOrderService;
import com.usian.skill.service.SkillService;
import com.usian.skill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * ClassName: MQReceiver
 * Author:   WGG
 * Date:    2022-12-2022/12/13-20:02
 * Version: 1.0
 * Description:
 */
@Component
@Slf4j
public class MQReceiver {


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SkillOrderService skillOrderService;

    @Autowired
    private SkillService skillService;

    @RabbitListener(queues = MQConfig.QUEUE)
    public void receive(String message){
        log.info("receive message: "+message);
        log.info("receive message: {}",message);
    }
    @RabbitListener(queues = MQConfig.SKILLQUEUE)
    public void receiveSkill(String message){
        log.info("receive message: "+message);
        log.info("receive message: {}",message);
        //将队列消息转换成对象
        SkillMessage skillMessage = JSON.parseObject(message, SkillMessage.class);

        //查库存
        GoodsVo goodsVo = goodsService.goodsVoByIdDB(skillMessage.getGoodsId());
        if (goodsVo.getStockCount()<=0){
            return ;
        }

        //判断用户是否重复秒杀
        SkillOrder skillOrder = skillOrderService.getOne(Wrappers.<SkillOrder>lambdaQuery()
                .eq(SkillOrder::getGoodsId, skillMessage.getGoodsId()).eq(SkillOrder::getUserId, Long.parseLong(skillMessage.getUserId())));
        //如果重复秒杀
        if (skillOrder!=null){
            return ;
        }

        skillService.skill(Long.parseLong(skillMessage.getUserId()),goodsVo);

    }
}
